<?php
# <!-- This file has functions related to the database -->

include_once("./configuration.php");

function get_relative_path($path) {

}

/* Connect to database server, select database and return true / false */
function db_connect() {
  global $dbhost;
  global $dbname;
  global $dbuser;
  global $dbpasswd;
  global $dbtype;

  if($dbtype=="MySQL") {
    if(!mysql_connect($dbhost, $dbuser, $dbpasswd))
      return false;
    if(!mysql_select_db($dbname))
      return false;
    return true;
  }
}

/* Makes a database query and returns true if user (arg) already exists. */
function user_exists($username) {
  global $dbtype;
  if(!db_connect())
    return false;
  if($dbtype == "MySQL") {
    $r = mysql_query("select * from users where username='".$username."'");
    if(mysql_num_rows($r) > 0) {
      return true; 
    }
  }
  return false;
}

/* Add new user to database.
 * Password is sha1'd with random user-specific salt 
 * Return TRUE on success and FALSE on failure.
 */
function db_add_user($username, $password, $realname, $organization) {
  global $dbtype;
  if(!db_connect())
    return false;
  $salt = substr(sha1(rand()), 0, 8);
  /* Validating DB input */
  $username = mysql_real_escape_string($username);
  $password = sha1($password.$salt);
  $realname = mysql_real_escape_string($realname);
  $organization = mysql_real_escape_string($organization);
  if(user_exists($username))
    return false;
  if($dbtype=="MySQL") {
     mysql_query("INSERT INTO users(username, passwd, salt) values('{$username}', '{$password}', '{$salt}')") or die(mysql_error());
     return true;
  }
  return false; // no DB type supported
}

/* Check password -function, called always when logging in to system.
 * Return user id on success and -1 on failure.
 */
function db_check_password($username, $password) {
  global $dbtype;
  if(!db_connect())
    return false;
  $username = mysql_real_escape_string($username);
  $q = mysql_query("SELECT passwd,salt FROM users where username = '{$username}'");
  $r = mysql_fetch_row($q);
  var_dump($r);
  $salt = $r[1];
  if($r[0] == sha1($password.$salt)) 
    return true;
  return false;
}

?>
